package com.ogawa.musicmodule

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.musicmodule.bean.*
import com.ogawa.projectcommon.appdatabase.AppDatabase
import com.ogawa.projectcommon.bean.MusicMixCollectBean
import com.ogawa.projectcommon.constants.IntentKeyConstant.LIVE_EVENT_BUS_KEY_MUSIC_CURTIME
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


const val MUSIC_SERVER_STATUS_SUSPEND = 1
const val MUSIC_SERVER_STATUS_PLAY_ING = 2
const val MUSIC_SERVER_STATUS_PLAY_RELAY = 3

const val MUSIC_SERVER_TYPE_NAIN = 1
const val MUSIC_SERVER_TYPE_MIX = 2


class MusicService : Service() {
    companion object {
        var curMusicPlayTime = 0.0f//当前播放的时长倒计时
        var playMainMusicBean = PlayMainMusicEvent("", "", 0)
        var playMixMusicBeans = ArrayList<PlayMixMusicBean>()

        //        var mediaPlayersMixVolumeList = ArrayList<JustMusicVolumeEvent>()
        init {
            playMixMusicBeans.add(PlayMixMusicBean("", "", 0, 0))
            playMixMusicBeans.add(PlayMixMusicBean("", "", 0, 1))
            playMixMusicBeans.add(PlayMixMusicBean("", "", 0, 2))
        }
    }

    private val mediaPlayersMixList: Array<MediaPlayer> =
        arrayOf(MediaPlayer(), MediaPlayer(), MediaPlayer())
    private var curTimeHandler: Handler? = null
    private var mediaPlayerMain = MediaPlayer()

    override fun onBind(intent: Intent): IBinder {
        return object : Binder() {}
    }


    var CHANNEL_ID_STRING = "CHANNEL_ID_STRING"
    var NOTICE_ID = 777
    var app_name = "app_name"

    override fun onCreate() {
        super.onCreate()
        curTimeHandler = Handler()
        curMusicPlayTime = MusicProjectSpUtils.getMusicAllTime()
        EventBus.getDefault().register(this)
        mediaPlayerMain = MediaPlayer()
        playMainMusicBean = MusicProjectSpUtils.getMusicLastName()

        val musicCollectDao = AppDatabase.get(this).getMixMusicCollectDao()
        for (daoItem in musicCollectDao.getAllMusic()) {
            for (bean in playMixMusicBeans) {
                if (daoItem.position == bean.index) {
                    bean.volume = daoItem.volume
                    bean.title = daoItem.name
                    bean.path = daoItem.localpath
                }
            }
        }
//        mediaPlayersMixVolumeList.add(JustMusicVolumeEvent().apply { index = 0 })
//        mediaPlayersMixVolumeList.add(JustMusicVolumeEvent().apply { index = 1 })
//        mediaPlayersMixVolumeList.add(JustMusicVolumeEvent().apply { index = 2 })
//        for (item in musicCollectDao.getAllMusic()){
//            for (volumeItem in mediaPlayersMixVolumeList){
//                if (item.position == volumeItem.index){
//                    volumeItem.value = item.volume
//                }
//            }
//        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        mediaPlayerMain.stop()
        mediaPlayerMain.release()
        for (item in mediaPlayersMixList) {
            item.stop()
            item.release()
        }
        curTimeHandler?.removeCallbacksAndMessages(null)
    }

    fun clearNotification(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val notificationManager: NotificationManager =
                applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.deleteNotificationChannel(CHANNEL_ID_STRING)
        } else{
            stopForeground(true)
        }

    }
    //开启通知栏
    fun startNotification(){
        //安卓8.0系统的特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager: NotificationManager =
                applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            var mChannel: NotificationChannel? = null
            mChannel = NotificationChannel(
                CHANNEL_ID_STRING,
                app_name,
                NotificationManager.IMPORTANCE_HIGH
            )
            //使通知静音
            mChannel.setSound(null, null)
            notificationManager.createNotificationChannel(mChannel)
            val notification = Notification.Builder(
                applicationContext, CHANNEL_ID_STRING
            ).build()
            startForeground(NOTICE_ID, notification)
            LogUtils.e("start Notification1")
            //8.0以前的bug，可创建相同id使该通知消失
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            val builder = Notification.Builder(this)
            //使通知静音
            builder.setSound(null, null)
            builder.setContentTitle(app_name)
            startForeground(NOTICE_ID, builder.build())
//            val intent = Intent(this, CancelNoticeService::class.java)
//            startService(intent)
            LogUtils.e("start Notification2")
        } else {
            startForeground(NOTICE_ID, Notification())
            LogUtils.e("start Notification3")
        }
    }

    fun stopAllMusic() {
        EventBus.getDefault().post(PlayMainMusicEvent("", "", MUSIC_SERVER_STATUS_SUSPEND))
        for (item in playMixMusicBeans) {
            EventBus.getDefault()
                .post(PlayMixMusicBean("", "", MUSIC_SERVER_STATUS_SUSPEND, item.index))
        }
    }

    /**
     * 调节音量
     */
    @Subscribe
    fun receiveJustMusicVolumeEvent(bean: JustMusicVolumeEvent) {
        when (bean.type) {
            MUSIC_SERVER_TYPE_NAIN -> {
                playMainMusicBean.volume = bean.value
                if (mediaPlayerMain.isPlaying) {
                    mediaPlayerMain.setVolume(
                        playMainMusicBean.volume,
                        playMainMusicBean.volume
                    )
                }
                playMainMusicBean.volume = bean.value
                MusicProjectSpUtils.setMusicLastName(playMainMusicBean)
            }
            MUSIC_SERVER_TYPE_MIX -> {
                if (bean.index < 0 || bean.index >= mediaPlayersMixList.size || bean.index >= playMixMusicBeans.size) {
                    return
                }
                playMixMusicBeans.get(bean.index).volume = bean.value
                if (mediaPlayersMixList[bean.index].isPlaying) {
                    mediaPlayersMixList[bean.index].setVolume(bean.value, bean.value)
                }
                val musicCollectDao = AppDatabase.get(this).getMixMusicCollectDao()
                for (item in musicCollectDao.getAllMusic()) {
                    if (item.position == bean.index) {
                        item.volume = bean.value
                        musicCollectDao.updateMusic(item)
                        break
                    }
                }
            }
        }
    }

    /**
     * 播放音乐
     */
    @Subscribe
    public fun receivePlayMainMusicEvent(bean: PlayMainMusicEvent) {
        if (bean.status == MUSIC_SERVER_STATUS_SUSPEND) {
            if (mediaPlayerMain.isPlaying) {
                mediaPlayerMain.pause()
            }
        } else if (bean.status == MUSIC_SERVER_STATUS_PLAY_ING) {
            mediaPlayerMain.pause()
            if (!bean.path.isEmpty()) {
                val parse = Uri.parse(bean.path)
                mediaPlayerMain = MediaPlayer.create(this, parse)
                mediaPlayerMain.isLooping = true
            }
            mediaPlayerMain.start()
            if (playMainMusicBean.volume > 0) {
                mediaPlayerMain.setVolume(
                    playMainMusicBean.volume,
                    playMainMusicBean.volume
                )
            }
        }
        bean.volume = playMainMusicBean.volume
        playMainMusicBean = bean
        MusicProjectSpUtils.setMusicLastName(playMainMusicBean)
    }

    @Subscribe
    fun receivePlayMixMusicBean(bean: PlayMixMusicBean) {
        if (bean.index < 0 || bean.index >= mediaPlayersMixList.size || bean.index >= playMixMusicBeans.size) {
            return
        }
        var mediaPlayer = mediaPlayersMixList[bean.index]
        var playMixMusicBean = playMixMusicBeans[bean.index]
        playMixMusicBean.title = bean.title
        playMixMusicBean.path = bean.path
        playMixMusicBean.status = bean.status
        if (bean.status == MUSIC_SERVER_STATUS_SUSPEND) {
            LogUtils.e("mix  ${bean.index} pause ${mediaPlayer}")
            mediaPlayer.pause()
        } else if (bean.status == MUSIC_SERVER_STATUS_PLAY_ING) {
            mediaPlayer.pause()
            if (!bean.path.isEmpty()) {
                val parse = Uri.parse(bean.path)
                mediaPlayer = MediaPlayer.create(this, parse)
                mediaPlayersMixList[bean.index] = mediaPlayer
                mediaPlayer.isLooping = true
            }
            LogUtils.e("mix  ${bean.index} start ${mediaPlayer}")
            mediaPlayer.start()
            if (playMixMusicBeans[bean.index].volume > 0) {
                mediaPlayer.setVolume(
                    playMixMusicBeans[bean.index].volume,
                    playMixMusicBeans[bean.index].volume
                )
            }

        }
        val musicCollectDao = AppDatabase.get(this).getMixMusicCollectDao()
        for (item in musicCollectDao.getAllMusic()) {
            if (item.position == bean.index) {
                item.status = playMixMusicBean.status
                musicCollectDao.updateMusic(item)
                break
            }
        }
    }

    /**
     * 更新混音列表
     */
    @Subscribe
    fun receiveUpdateMixMusicBean(bean: MusicMixCollectBean) {
        for (item in playMixMusicBeans) {
            if (bean.position == item.index) {
                item.path = bean.localpath
                item.title = bean.name
                item.volume = bean.volume
                item.status = MUSIC_SERVER_STATUS_PLAY_RELAY
            }
        }

    }


    @Subscribe
    fun receiveChangeMusicAllTimeEvent(bean: ChangeMusicAllTimeEvent) {
        val musicAllTime = MusicProjectSpUtils.getMusicAllTime()
        curMusicPlayTime = musicAllTime
        LiveEventBus.get(LIVE_EVENT_BUS_KEY_MUSIC_CURTIME)
            .post(UpdateMusicCurrentTimeEvent(curMusicPlayTime))
    }
    @Subscribe
    fun receiveMusicStartOrStopEvent(bean: MusicStartOrStopEvent) {
        if (bean.isStart) {
            startNotification()
            curTimeHandler?.post(object : Runnable {
                override fun run() {
                    curMusicPlayTime -= 10
                    LiveEventBus.get(LIVE_EVENT_BUS_KEY_MUSIC_CURTIME)
                        .post(UpdateMusicCurrentTimeEvent(curMusicPlayTime))
                    if (curMusicPlayTime > 0) {
                        curTimeHandler?.removeCallbacksAndMessages(null)
                        curTimeHandler?.postDelayed(this, 10 * 1000)
                        val musicAllTime = MusicProjectSpUtils.getMusicAllTime()
                        LogUtils.e(
                            "UpdateMusicCurrentTimeEvent",
                            "allTime: ${musicAllTime}   cur:${curMusicPlayTime}"
                        )
                    } else {
                        stopAllMusic()
                    }
                }
            })
        } else {
            clearNotification()
            curTimeHandler?.removeCallbacksAndMessages(null)
        }
    }


}